<!-- 导师业务经费发放管理 -->
<template>
    <div class="con">
        <div>
            <ConditionCard shadow="never" body-style="padding: 24px 24px 6px 24px;" @search="onSubmit(true)" @reset="reset">
                <el-form ref="queryForm" label-suffix="：" :model="queryForm" label-position="right" label-width="120px">
                    <el-row :gutter="24">
                        <el-col :span="8">
                            <el-form-item :label="$t('fundDistribution.sendYear')">
                                <DictSelect v-model="queryForm.issueYear" :data="options.issueYear" filterable :clearable="false" v-clearreadonly></DictSelect>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('label.grade')">
                                <DictSelect v-model="queryForm.currentGrade" :data="options.currentGrade" filterable :clearable="true" v-clearreadonly></DictSelect>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                          <el-form-item :label="$t('label.trainingLevel')">
                              <DictSelect v-model="queryForm.eduLevel" :data="options.eduLevel" :clearable="true" v-clearreadonly></DictSelect>
                          </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="24">
                        <el-col :span="8">
                            <el-form-item :label="$t('label.trainingCategory')" >
                                <DictSelect v-model="queryForm.eduMode" :filterable="true" :data="options.eduMode" :clearable="true" v-clearreadonly></DictSelect>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('label.degreeCategory')">
                                <DictSelect v-model="queryForm.degreeType" :data="options.degreeType" :clearable="true"></DictSelect>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('label.formLearning')">
                                <DictSelect v-model="queryForm.studyForm" :data="options.studyForm" :clearable="true"></DictSelect>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="24">
                        <el-col :span="8">
                            <el-form-item :label="$t('label.college')">
                              <DictSelect
                                v-model="queryForm.faculty"
                                clearable
                                filterable
                                :placeholder="$t('common.text.all')"
                                :data="options.academyId"
                                v-clearreadonly
                              >
                              </DictSelect>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('label.major')">
                              <MyMajor :faculty="queryForm.faculty" :filterable="true" v-model="queryForm.profession" v-clearreadonly> </MyMajor>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                          <el-form-item :label="this.$t('standardSetting.categories')">
                            <DictSelect
                              v-model="queryForm.category"
                              filterable
                              :data="options.categories"
                              v-clearreadonly>
                            </DictSelect>
                          </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="24">
                        <el-col :span="8">
                          <el-form-item :label="$t('paperBlindTrial.students')">
                            <el-select
                              v-model="queryForm.stuNo"
                              :remote-method="selectStu"
                              :placeholder="$t('fundDistribution.stuNoPlaceholder')"
                              filterable
                              remote
                              style="width: 100%;"
                              :clearable="true"
                              v-clearreadonly
                            >
                              <el-option
                                v-for="item in students"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                              />
                            </el-select>
                          </el-form-item>
                        </el-col>
                        <el-col :span="8">
                          <el-form-item :label="$t('achievementApply.teacherName')">
                            <el-select
                              v-model="queryForm.tutorNo"
                              :remote-method="selectUser"
                              :placeholder="$t('preDefense.teacherNameTips')"
                              filterable
                              remote
                              style="width: 100%;"
                              :clearable="true"
                              v-clearreadonly
                            >
                              <el-option
                                v-for="item in users"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                              />
                            </el-select>
                          </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('fundDistribution.isAdjust')">
                                <DictSelect v-model="queryForm.isAdjust" :data="options.yesNo" :clearable="true"></DictSelect>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="24">
                      <el-col :span="8">
                        <el-form-item :label="this.$t('fundDistribution.isEffective')">
                            <DictSelect v-model="queryForm.enableStatus" :data="options.yesNo" :clearable="true"></DictSelect>
                        </el-form-item>
                      </el-col>
                    </el-row>
                </el-form>
            </ConditionCard>
            <el-card shadow="never" body-style="padding: 24px;">
              <div class="edu-opertion-bar">
                  <div class="float-left">
                    <h1 class="condition-title">{{$t('fundDistribution.titleLabel')}}</h1>
                    <!-- <KeywordInput v-model="queryForm.ruleName" :placeholder="$t('achievementApply.rulePlaceholder')" @enter="search"></KeywordInput> -->
                  </div>
                  <div class="float-right" v-if="btnState">
                      <el-button @click="batchName" type="primary">{{$t('fundDistribution.batchBtn')}}</el-button>
                      <el-button @click="exportFunc" type="primary">{{$t('message.export')}}</el-button>
                      <el-button @click="open('')" type="primary">{{$t('message.add')}}</el-button>
                  </div>
              </div>
              <edu-table ref="tables" :url="tableApi"  @selection-change="handleSelectionChange" :orderFixed="true">
                  <el-table-column :min-width="item.width" v-for="item in label" :fixed="item.fixed" :key="item.props" :label="item.label" :prop="item.props" show-overflow-tooltip></el-table-column>
                  <el-table-column :min-width="80" :label="this.$t('fundDistribution.isAdjust')" fixed="right">
                    <template slot-scope="scope">
                      <el-tag
                        :type="getType(scope.row.isAdjust, 'isAdjust')"
                      >{{ getStatus(scope.row.isAdjust, 'isAdjust') }}</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column :min-width="80" :label="this.$t('fundDistribution.isEffective')" fixed="right">
                    <template slot-scope="scope">
                      <el-tag
                        :type="getType(scope.row.enableStatus, 'enableStatus')"
                      >{{ getStatus(scope.row.enableStatus, 'enableStatus') }}</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column width="90px" :label="$t('nonPublicCourseOpen.operation')" fixed="right" v-if="btnState">
                      <template slot-scope="scope">
                          <div class="con_btns" @click.stop="">
                              <el-button type="text" @click="open('edit', scope.row)">{{$t('message.edit')}}</el-button>
                              <el-button type="text" v-if="scope.row.enableStatus === '0'" @click="failureFunc(scope.row)">{{$t('fundDistribution.effective')}}</el-button>
                              <el-button type="text" v-else @click="failureFunc(scope.row)">{{$t('fundDistribution.Invalidation')}}</el-button>
                          </div>
                      </template>
                  </el-table-column>
              </edu-table>
            </el-card>
        </div>
        <!-- 申请 -->
        <distributionAdd ref="distributionAdd" :objs="objs" :options="options" @emit:back="applyBack"></distributionAdd>
    </div>
</template>

<script>
import { queryDistribution, distributionStatusChange,
  distributionExport, distributionBatchAddList, distributionQuery } from "common/src/api/fundManagement/standardSetting";
import distributionAdd from './distributionAdd';
import examinationStudentsApi from "common/src/api/welcomeService/examinationStudents";//导出
import commonMixins from 'common/src/views/practiceManagement/commonMixins';
import { getAllMajorList } from "common/src/api/resource/course";
import { findTeacherInfoList, findStuInfoListForSelect } from 'common/src/api/studentinfo';
import MyMajor from "common/src/views/administrator/undergraduateTutor/component/MyMajor";
import mixin from 'common/src/mixins/index';
export default {
    components: {
      distributionAdd,
      MyMajor
    },
    mixins: [commonMixins,mixin],
    data() {
        return {
            tableApi: queryDistribution,
            objs: {
              editFlag: false
            },
            queryForm: {
              issueYear: '',
              currentGrade: '',
              eduLevel: '',
              eduMode: '',
              degreeType: '',
              studyForm: '',
              faculty: '',
              profession: '',
              category: '',
              stuNo: '',
              tutorNo: '',
              isAdjust: '',
              enableStatus: ''
            },
            label: [
                { label: this.$t('fundDistribution.year'), props: 'issueYear', width: 60,fixed:'left'},
                { label: this.$t('label.stuCode'), props: 'stuNo', width: 80,fixed:'left' },
                { label: this.$t('label.grade'), props: 'currentGrade', width: 90,fixed:'left' },
                { label: this.$t('label.stuName'), props: 'stuName', width: 90,fixed:'left' },
                { label: this.$t('label.trainingLevel'), props: 'eduLevelI18n', width: 90 },
                { label: this.$t('label.trainingCategory'), props: 'eduModeI18n', width: 100 },
                { label: this.$t('label.degreeCategory'), props: 'degreeTypeI18n', width: 90 },
                { label: this.$t('label.formLearning'), props: 'studyFormI18n', width: 90 },
                { label: this.$t('fundDistribution.tutorNum'), props: 'tutorNo', width: 95 },
                { label: this.$t('paperBlindTrial.stuTutorName'), props: 'tutorName', width: 95 },
                { label: this.$t('label.college'), props: 'facultyI18n', width: 150 },
                { label: this.$t('standardSetting.categories'), props: 'categoryI18n', width: 95 },
                { label: this.$t('fundDistribution.fundingStandard'), props: 'fundsStandard', width: 95 },
                { label: this.$t('fundDistribution.actualExpenses'), props: 'actualFunds', width: 95 },
            ],
            options: {
                academyId: [], // 学院
                issueYear: [], // 发放年度
                currentGrade: [], // 年级
                eduLevel: [], // 培养层次
                eduMode: [], // 培养类别
                degreeType: [], // 学位类型
                studyForm: [], // 学习形式
                passCount: [], // 通过次数
                yesNo: [
                  { label: this.$t('message.yes'), value: '1' },
                  { label: this.$t('message.no'), value: '0' }
                ],
                isAdjust: [
                  { label: this.$t('fundDistribution.adjusted'), value: '1', type: 'success' },
                  { label: this.$t('fundDistribution.unadjusted'), value: '0', type: 'info' }
                ],
                enableStatus: [
                  { label: this.$t('fundDistribution.effective'), value: '1', type: 'success' },
                  { label: this.$t('fundDistribution.invalid'), value: '0', type: 'info' }
                ],

            },
            selectionDatas: [],
            students: [],
            users: [],
            btnState: false
        };
    },
    computed: {

    },
    created() {
    },
    mounted() {
      let currentYear = moment().year();
      let maxYear = currentYear + 1;
      // 获取数据字典数据
      let param = {
        X_YX: 'academyId', // 学院
        X_PYCC: 'eduLevel', // 培养层次
        X_PYLB: 'eduMode', // 培养类别
        X_XWLX: 'degreeType', // 学位类型
        X_XXXS: 'studyForm', // 学习类型

      };
      this.initOptions(param);
      this.getCategories();
      for (let i = 0; i <= 50; i++) {
        let showYear = maxYear - i;
        let gradeYear = currentYear - i;
        this.options.issueYear.push(
          {
            label: showYear,
            value: showYear
          }
        );
        this.options.currentGrade.push(
          {
            label: gradeYear,
            value: gradeYear
          }
        );
      }
      this.queryForm.issueYear = currentYear;
      this.onSubmit(true);
      this.btnState = this.global.isAdmin;
    },
    methods: {
      open(val, row = {}) {
        if (val === 'edit') { // 修改
          this.objs.editFlag = true;
          this.$refs.distributionAdd.titles = this.$t('message.edit');
          this.$refs.distributionAdd.getDetail(row.id);
        } else { // 新增
          this.$refs.distributionAdd.titles = this.$t('message.add');
          this.objs.editFlag = false;
        }
        this.$refs.distributionAdd.dialogFlag = true;
        this.$refs.distributionAdd.form.issueYear = this.queryForm.issueYear;
      },
      // 多选方法
      handleSelectionChange (val) {
        this.selectionDatas = val;
      },
      onSubmit(refresh) { // 筛选
        if (refresh) {
          this.$refs.tables.pageNum = 1;
        }
        this.$refs.tables.search(this.queryForm);
      },
      reset() {  // 重置
        for (const key in this.queryForm) {
          this.queryForm[key] = '';
        }
        this.queryForm.issueYear = moment().year();
        this.onSubmit(true);
      },
      search() { // 搜索
        this.queryForm.ruleName = this.queryForm.ruleName.trim();
        this.onSubmit(true);
      },
      // 申请回调方法
      applyBack () {
        this.onSubmit(true);
      },
      getStatus(val, key) {
        let option = this.options[key].find(v => v.value == val)
        return option ? option.label : null
      },
      getType(val, key) {
        let option = this.options[key].find(v => v.value == val)
        return option ? option.type : null
      },
      // 查询学生信息接口
      selectStu (query) {
        if (!query) return;
        const data = {
          name: query,
          pageNum_: 1,
          pageSize_: 50
        }
        this.loading = true
        findStuInfoListForSelect(data)
          .then(res => {
            this.loading = false
          if (res.code == 200) {
              this.students = this.transData(res.data.list, 'name', 'studentId')
            } else throw res.code
          })
          .catch(error => {
              this.loading = false
              this.$message({
                  type: 'error',
                  message: '查询用户出错'
              })
          })
      },
      selectUser(query) {
        if (!query) return
        const data = {
            condition: query,
            pageNum_: 1,
            pageSize_: 10
        }
        this.loading = true;
        findTeacherInfoList(data)
          .then(res => {
              this.loading = false
              if (res.code == 200) {
                  this.users = this.transData(res.data.list, 'name', 'code')
              } else throw res.code
          })
          .catch(error => {
            this.loading = false
            this.$message({
                type: 'error',
                message: '查询用户出错'
            })
          });
      },
      transData(list, name, code) {
        return list.map((item, index, array) => {
          return {
            label: item[name] + '(' + item[code] + ')',
            value: item[code]
          }
        })
      },
      //  获取门类
      getCategories() {
        let data = {
            level: 1,
            type: 1,
            page: false
        };
        getAllMajorList(data).then(res => {
            if (res.code == 200) {
                this.options.categories = res.data.list.map(c => {
                    return {
                        label: c.name,
                        value: c.code
                    };
                });
            }
        });
      },
      // 失效/有效 方法
      failureFunc(row) {
        if (row.enableStatus === '1') { // 有效转失效
          this.$eduConfirm(
            this.$t('fundDistribution.InvalidationMsg'),
            this.$t('fundDistribution.Invalidation')
          ).then(() => {
            let param = {
              "id": row.id,
              "enableStatus": "0" //1-有效，0失效
            };
            this.sendChange(param);
          });
        } else { // 失效转有效
          this.$eduConfirm(
            this.$t('fundDistribution.effectiveMsg'),
            this.$t('fundDistribution.effective')
          ).then(() => {
            let param = {
              "id": row.id,
              "enableStatus": "1" //1-有效，0失效
            };
            this.sendChange(param);
          });
        }
      },
      // 有效、失效请求发送
      sendChange(param){
        distributionStatusChange(param).then(res=>{
          if (res.code === 200) {
            this.$message.success(this.$t('course.operateSuccess'));
            this.onSubmit(true);
          }
        });
      },
      // 批量生成名单
      batchName () {
        // 根据年度生成名单的时候需要查询一下该年度是否已有名单，有则需要提示
        let queryParam = {
          "pageNum_": 1,
          "pageSize_": 10,
          "condition": {
            issueYear: this.queryForm.issueYear
          }
        };
        distributionQuery(queryParam).then(res=>{
          if (res.code === 200 && res.data.list.length > 0) {
            this.$eduConfirm(
              this.$t("fundDistribution.batchMsg"),
              this.$t("fundDistribution.batchTips")
            ).then(() => {
              this.addListFunc();
            });
          } else {
            this.addListFunc();
          }
        });
      },
      // 批量生成名单调用方法
      addListFunc() {
        let param = {
          issueYear: this.queryForm.issueYear
        };
        distributionBatchAddList(param).then(res=>{
          if (res.code === 200 && !res.data) {
            this.$message.success(this.$t('course.operateSuccess'));
            this.onSubmit(true);
          } else if (res.code === 200 && res.data && res.data.length > 0) {
            let messageInfo = '';
            res.data.forEach(item =>{
              let oneInfo = '标准（' + item + '）有冲突；';
              messageInfo += oneInfo;
            });
            messageInfo += '无法生成名单，请先修改经费标准设置';
            this.$eduAlert(messageInfo, '提示');
          }
        });
      },
      //列表信息导出
      exportFunc() {
        let loading = this.$loading({
          lock: true,
          text: "Loading",
          spinner: "el-icon-loading",
          background: "rgba(255, 255, 255, .48)"
        });
        let jsons = this.selectionDatas;
        let param = {};
        param.rows = jsons;
        param.exportCondition = this.queryForm;
        if (jsons && jsons.length > 0) { // 优先按勾选内容导出
          param.exportType = 1;
        } else { // 存在搜索条件时则按搜索条件导出
          param.exportType = 0;
        }
        distributionExport(param).then(res => {
          if (res.code == 200) {
            this.delayRequest(res.data.key, loading);
          } else {
            loading.close();
          }
        });
      },
      async delayRequest(key, loading) {
        await new Promise(resolve => setTimeout(resolve, 5000));
        examinationStudentsApi.getReportStatus(key).then(res => {
          if (res.code == 200 && res.data.status) {
            let path = examinationStudentsApi.exportUrl + res.data.path;
            window.location.href = path;
            loading.close();
          } else {
            this.delayRequest(key, loading);
          }
        })
        .catch(ex => {
          this.$message({
            type: "error",
            message: "导出失败"
          });
        });
      },
    }
};
</script>

<style scoped lang="scss">
</style>

